import Mn from 'backbone.marionette';
import Radio from 'backbone.radio';
import ModalBehavior from 'base/behaviors/ModalBehavior';
import SelectWidget from 'widgets/SelectWidget';
import { serializeForm } from '../../../tools';

const template = require('./templates/AddCriterionView.mustache');

const AddCriterionView = Mn.View.extend({
    template: template,
    className: 'main_content',
    behaviors: [ModalBehavior],
    template: template,
    regions: {
        entityField: '.field-entity',
        keyField: '.field-key'
    },
    ui: {
        form: 'form',
        submit: "button[type=submit]",
        reset: "button[type=reset]"
    },
    events: {
        'submit @ui.form': 'onSubmitForm',
        'click @ui.reset': 'onCancelClick',
        'click @ui.submit': 'onSubmitForm'
    },
    childViewEvents: {
        'finish:relationship': 'onRelationshipFinish',
    },
    childViewTriggers: {},
    initialize(options){
        this.statService = Radio.channel('stat');
        this.facade = Radio.channel('facade');
        this.mergeOptions(options, ['attributePath', 'parentPath'])
        console.log("Add Criterion form");
        console.log("Attribute tree path");
        console.log(this.attributePath);
        console.log(this.parentPath);
    },
    getFieldValue(key){
        /*
            Find the field value in the form object
         */
        const values = serializeForm(this.getUI('form'));
        let field_value;
        if (key in values){
            field_value = values[key];
        }
        return field_value
    },
    getPath(field_value) {
        /*
           Return the current path in the attribute tree for the given key
        */
        if (! field_value){
            field_value = this.parentPath || this.getFieldValue('relationship');
        }
        
        let path = [...this.attributePath];
        if (field_value){
            path.push(field_value);
        }
        return path;
    },
    onSubmitForm(event){
        // On merge les données de formulaire avec le model tel qu'il a été initialisé
        // et les méta données de la colonne qui a été sélectionnée
        event.preventDefault();
        console.log("Submitting");
        const values = serializeForm(this.getUI('form'));
        const key = values['key'];

        const path = this.getPath();
        console.log("   Path of the current model %s", path);
        const column_def = this.statService.request('find:column', key, path)

        this.model.set(values);
        console.log(this.model.attributes);
        this.model.set(column_def);
        console.log(this.model.attributes);
        this.facade.trigger('criterion:add', this.model);
        this.trigger('modal:close');
    },
    onCancelClick(){
        console.log("Cancel clicked");
        this.triggerMethod('reset:model');
        let eventName = 'modal:close';
        this.triggerMethod(eventName);
    },
    showKeySelect(relationship){
        console.log("showKeySelect");
        const path = this.getPath(relationship);
        const options = this.statService.request('get:attributes', path);
        console.log(options);
        const view = new SelectWidget({
            options: options,
            label: "Type de critère",
            id_key: 'name',
            field_name: "key"
        });
        this.showChildView("keyField", view);
    },
    onRelationshipFinish(field_value){
        /*
        Fired when the type of criterion was selected
        */
        console.log("onRelationshipFinish");
        let path = this.getPath(field_value);
        this.model.set('relationship', field_value);
        this.showKeySelect(field_value);
    },
    onRender(){
        console.log(this.statService);
        const options = Object.values(this.statService.request('get:relationships', this.attributePath));
        console.log(options);
        options.splice(0, 0, {'label': 'Entité', name: ''})

        const view_opts = {
            options: options,
            label: "Type de critère",
            id_key: 'name',
            field_name: "relationship"
        };
        if (this.parentPath){
            console.log("")
            view_opts['editable'] = false;
            view_opts['value'] = this.parentPath;  
        }
        const view = new SelectWidget(view_opts);
        this.showChildView("entityField", view);
        this.showKeySelect();
    },
});
export default AddCriterionView